package com.kgc.web.listener; /**
 * <h3>项目名称:demo03050</h3>
 * <p>本API描述:${description}</p>
 * <p>@author : AliyZhang</p>
 * <p>@date : 2021-03-08 13:05</p>
 **/

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
/*
* 该监听器对象有servlet容器创建
* 监听会话的创建和销毁
*/
@WebListener
public class MyHttpSessionListener implements HttpSessionListener {

    public MyHttpSessionListener() {
    }

    //只要一个会话产生，监听器就会调用该方法
    @Override
    public void sessionCreated(HttpSessionEvent event) {
        //获取session对象，进而获取application对象
        ServletContext application = event.getSession().getServletContext();
        Object connTotal = application.getAttribute("connTotal");
        if(connTotal==null){
            application.setAttribute("connTotal",1);
        }else {
            application.setAttribute("connTotal",((int)connTotal)+1);
        }
    }

    //会话超时或被销毁是调用
    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        ServletContext application = event.getSession().getServletContext();
        Object connTotal = application.getAttribute("connTotal");
        application.setAttribute("connTotal",((int)connTotal)-1);
    }
}
